<?php
class Core_Controller_Action extends Zend_Controller_Action 
{
	public $userData;
	
	public $menu;
	
	public $config;
	
	public $hrefMapper = array();
	
	public $translates;
	
	public $locale = false;
	
	public $serverName;
	
	public $localeArr = array(
		'pl' => 'pl', 
		'en' => 'en', 
		'cs' => 'cs'
	);
	
	public $basket;
	
	public function init() {
	}
	
	public function preDispatch() {		
		$this->serverName = 'http://' . $_SERVER['SERVER_NAME'];
		
		$this->hrefMapper = array(
			'cp' => 'Strona główna',
			'cpstructure' => 'Struktura',
			'cpgaleries' => 'Galerie',
			'cpmanufacturers' => 'Producenci',
			'cpvat' => 'Vat',
			'cptags' => 'Tagi',
			'cpmagazine' => 'Magazyn',
			'cpcurrency' => 'Waluty',
			'cpshipping' => 'Przesyłki',
			'cporders' => 'Zamówienia',
			'cpcodes' => 'Kody rabatowe',
			'cpnewsletter' => 'Newsletter',
			'cpusers' => 'Użytkownicy',
			'cpnews' => 'Aktualności',
			'cpproducts' => 'Produkty',
			'cpagent' => 'Agent',
			'cpsetings' => 'Ustawienia'
		);
		
		try {
			$this->sessionData = new Zend_Session_Namespace('sessionData');
		} catch( Exception $e ) {
			$this->sessionData = new Zend_Session_Namespace('sessionData');
		}

		if( $this->sessionData->locale && isSet( $this->localeArr[$this->sessionData->locale] ) ) {
			$this->locale = $this->sessionData->locale;
		}

		if( !isSet( $this->sessionData->basket ) ) {
			$this->sessionData->basket = array(
				'iden' => time() . '-' . substr(md5(date("d.m.Y.H.i.s").rand(1,1000000)) , 0 , 5),
				'items' => array()
			);
		}

		if( isSet( $_GET['lang'] ) && isSet( $this->localeArr[$_GET['lang']] ) ) {
			$this->sessionData->locale = $_GET['lang'];
			$this->locale = $_GET['lang'];
		}
		
		if( !$this->locale ) {
			$this->sessionData->locale = 'pl';
			$this->locale = 'pl';
		}
		
    	$auth = Zend_Auth::getInstance();

    	$this->view->oper = intval( $this->_request->getParam( 'oper' ) );
    	
    	$this->config = Zend_Registry::get('config');
	
    	$this->view->config = $this->config;
    	
    	$this->view->requestUri = $this->_request->getRequestUri();
    	
		if($auth->hasIdentity()) {
			$this->userData = $auth->getIdentity();
			$userRole = $this->userData->role;

			$this->view->menu = Core_Menu::get( $userRole );
			$this->view->userData = $this->userData;
			$this->view->logged = true;
			$this->view->controllerName = $this->_request->getControllerName();
			
			$this->view->yih = isSet( $this->hrefMapper[$this->view->controllerName] ) ?
				$this->hrefMapper[$this->view->controllerName] : '';

			if(  substr( $this->_request->getControllerName(), 0, 2 ) == 'cp' ) {
				/*
				 * wczytywanie menu admina
				 */
				$menuConfig = new Zend_Config_Xml( $this->config['service']['config'] . '/menu_admin.xml', 'role'.$userRole );
				$menuConfig = $menuConfig->toArray();
				$this->view->menuAdmin = $menuConfig['name']['action'];
			} else {
				$this->_helper->layout()->setLayout('layout_service');
			}
			
		} else {
			$userRole = 0;
			$this->userData = false;
			$this->view->logged = false;

			if( 
				substr( $this->_request->getControllerName(), 0, 2 ) == 'cp'
			 ) {
				if( $this->_request->getActionName() != 'auth' ) {
					$this->_redirect( 'cp/auth' );
					exit;
				}
			}else {
				$this->_helper->layout()->setLayout('layout_service');
			}
		}
		//var_dump($this->userData);die();
		$acl = new Zend_Acl();

		/*
		 * pobieranie ról dla użytkowników
		 */
		$rolesConfig = new Zend_Config_Xml( $this->config['service']['config'] . '/acl.xml', 'roles' );
		
		/*
		 * Tablica z zasobami, które zostaną dodane do ACL-a
		 */
		$addedResource = array();
		
		foreach( $rolesConfig->role->toArray() as $role ) {
			
			/*
			 * dodawanie roli do acl-a
			 */
			$acl->addRole( new Zend_Acl_Role( $role['value'] ) );
			/*
			 * wczytania akcji dla roli
			 */
			foreach( $role['actions']['action'] as $allowActionsValue ){
				if( !array_key_exists( $allowActionsValue, $addedResource ) ) {
					$acl->add( new Zend_Acl_Resource( $allowActionsValue ) );
					$addedResource[$allowActionsValue] = true;
				}
				$acl->allow( $role['value'], $allowActionsValue );
			}
		
		}
		
		//Core_Debug::pr( $this->config );die(1);
		
		$this->_setTranslate( $this->config['translations']['dir'], $this->config['path']['dir'] );
		
		$this->view->requestUri = $this->_request->getRequestUri();
		$this->view->requestUriClean = str_replace( $this->view->baseUrl() . '/', '', $this->_request->getRequestUri() );
		$this->view->controllerName = $this->_request->getControllerName();
		$this->view->actionName = $this->_request->getActionName();

		/*
		 * sprawdzanie czy istnieje dostęp do żądanego zasobu
		 */
		$userAction = $this->_request->getControllerName() . '/' . $this->_request->getActionName();
		if( $acl->has($userAction) ) {
			if( !$acl->isAllowed( $userRole, $userAction ) ) {
				$this->_redirect( 'index/account/?ref=' . $userAction );
			}
		} else {
			$this->_redirect( $this->config['service']['error_404'] );
		}
		
		/*
		 * koszyk
		 */
		$priceRank = ( ( $this->userData ) && ( intval( $this->userData->price_rank ) > 0 ) ) ? $this->userData->price_rank : 1;
		$this->basket = new Core_Basket( $this->locale, $this->userData, $priceRank );
		$this->view->basket = $this->basket;
		$this->basket->sumAll();
		
		
		/* lista najnowszych produktów wyswietlana na każdej podstronie */
		$Products = new Products();
		if( !$this->userData ) {
			$items = $Products->getListService( 2, array(
				'r1' => 'yes'
			) );

			$this->view->listnewest = $items;
		} else {
			$sess = new Zend_Session_Namespace( 'ranks' );
			
			if( count( $sess->data ) > 0 ) {
				$items = $Products->getListService( 2, false, $sess->data );
			} else {
				$items = $Products->getListService( 2, array(
					'r1' => 'yes'
				) );
			}
			$this->view->listnewest = $items;
		}

		if( !$this->userData ) {
			$this->view->listspecialrand = $Products->getListSpecialService( array(
				'r1' => 'yes'
			), 1, true );
			$this->view->priceRank = 1;
		} else {
			$this->view->listspecialrand = $Products->getListSpecialService( array(
				'r' . $priceRank => 'yes'
			), 1, true );
			$this->view->priceRank = $priceRank;
		}
		
		/* lista najnowszych artykułów z akademii */
		$News = new News();
		$this->view->listacademy = $News->getListService( 3 );
		
		/* pliki z cennikiem i katalogiem */
		$Settings = new Settings();
		$ob = $Settings->getItemById(1);
		if( $ob ) {
			$this->view->cennik = $ob->value;
		}
		
		/* ilość obserwowanych */
		if( $this->userData ) {
			$Wishlist = new Wishlist();
			
			$cntw = $Wishlist->getCountService( $this->userData->u_id );
			$this->view->wishlistCnt = count( $cntw );
		} else {
			$this->view->wishlistCnt = 0;
		}
	
//		$ob = $set->getItemById(2);
//		if( $ob ) {
//			$this->view->katalog = $ob->value;
//		}
	}
	
    private function _setTranslate( $translates, $path ) {
    	$this->translates = new Zend_Config_Xml( $translates, 'files' );

    	$transArr = $this->translates->toArray();
    	$i = 0;
    	foreach( $transArr['path'] as $value ) {
    		if( $i == 0 ) {
    			$translate = new Zend_Translate( 'array', $path . $value['file'], $value['locale'] );
    		} else {
    			$translate->addTranslation( $path . $value['file'], $value['locale'] );
    		}
    		
    		$i++;
    	}
    	
    	//$translate = new Zend_Translate( 'array', '/opt/lampp/htdocs/keye_svn/application/translations/pl/navigator.php', 'pl' );
    	//$translate->addTranslation( '/opt/lampp/htdocs/keye_svn/application/translations/en/navigator.php', 'en' );

    	$this->view->translate()->setTranslator($translate);
    	
    	$this->view->translate()->setLocale( $this->locale );
    	
    	$this->view->assign( 'locale', $this->locale );
    }
}